import maya.cmds as mc
import re
import maya.OpenMaya as om
import commonScripts02
reload(commonScripts02)

class LZ_rivet(commonScripts02.commonScripts):
    def fixedCtrl(self,rivetObj,IFrotate,IFMO):
        motherType=self.getObjType(rivetObj)
        
        if motherType=='kMesh'or motherType=='kNurbsSurface':
            obj=mc.ls(sl=True)
            inputmesh=rivetObj
            
            if motherType=='kMesh':
                
                mc.createNode('closestPointOnMesh',n='fixedNode')
            
            if motherType=='kNurbsSurface':
                
                mc.createNode('closestPointOnSurface',n='fixedNode')
                
            meshshape=mc.listRelatives(inputmesh,s=True)[0]
            meshMatrix=str(meshshape)+'.worldMatrix[0]'
            if motherType=='kMesh':
                meshout=str(meshshape)+'.outMesh'
            if motherType=='kNurbsSurface':
                meshout=str(meshshape)+'.local'
            follicleAll=[]
            
            if mc.objExists('follicle_grp'):
                pass
            else:
                mc.group(em=True,n='follicle_grp')
                
            for i in obj:
                folliclename=str(i)+'_follicleshape'
                mc.createNode('follicle',n=folliclename)
                follicleparent=mc.listRelatives(folliclename,p=True)[0]
                follicleparentname=str(i)+'_follicle'
                mc.rename(follicleparent,follicleparentname)
                
                mc.connectAttr(meshMatrix,str(folliclename)+'.inputWorldMatrix')
                if motherType=='kMesh':
                    mc.connectAttr(meshout,str(folliclename)+'.inputMesh')
                    matrixconnect=mc.listConnections('fixedNode.inMesh')
                    if matrixconnect==None:
                        mc.connectAttr(meshout,'fixedNode.inMesh')
                if motherType=='kNurbsSurface':
                    mc.connectAttr(meshout,str(folliclename)+'.inputSurface')
                    
                
                    matrixconnect02=mc.listConnections('fixedNode.inputSurface')
                    if matrixconnect02==None:
                        mc.connectAttr(meshout,'fixedNode.inputSurface')
                        print(1)
                    
         #      add a temporary group to connect it's translate to fixednode'inposition because of getting wrong location information if there are other groups above it
                
                mc.group(em=True,n='temporarygrp')
                mc.parentConstraint(i,'temporarygrp',maintainOffset=False)
         #########
               
                mc.connectAttr('temporarygrp.translate','fixedNode.inPosition')
                
                mc.connectAttr(str('fixedNode')+'.parameterU',str(folliclename)+'.parameterU')
                mc.connectAttr(str('fixedNode')+'.parameterV',str(folliclename)+'.parameterV')
                
                mc.connectAttr(str(folliclename)+'.outTranslate',str(follicleparentname)+'.translate')
                mc.connectAttr(str(folliclename)+'.outRotate',str(follicleparentname)+'.rotate')
                
                locparameterU=mc.getAttr(str(follicleparentname)+'.parameterU')
                locparameterV=mc.getAttr(str(follicleparentname)+'.parameterV')
                
                mc.disconnectAttr('fixedNode.parameterU',str(follicleparentname)+'.parameterU')
                mc.disconnectAttr('fixedNode.parameterV',str(follicleparentname)+'.parameterV')
                
                mc.setAttr('fixedNode.parameterU',locparameterU)
                mc.setAttr('fixedNode.parameterV',locparameterV)
                
                
                if IFrotate==True:
                    mc.parentConstraint(follicleparentname,i,maintainOffset=IFMO)
                else:
                    mc.pointConstraint(follicleparentname,i,maintainOffset=IFMO)
                        
                mc.disconnectAttr('temporarygrp.translate','fixedNode.inPosition')
                follicleAll.append(follicleparentname)
                mc.delete('temporarygrp')
                
            mc.parent(follicleAll,'follicle_grp')
            mc.delete('fixedNode')
        
        if motherType=='kNurbsCurve':
            curvename=rivetObj
            
            objsel=mc.ls(sl=True)
            shapecurve=mc.listRelatives(curvename,s=True)[0]
            
            num=0
            for i in objsel:
                namePoci=str(i)+'_poci'
                mc.createNode('pointOnCurveInfo',n=namePoci)[0]
                parameter=self.getParam(curvename , i)
                mc.select(cl=True)
                templeloc=str(i)+'rivetLoc'
                mc.spaceLocator(n=templeloc)
                mc.connectAttr(str(shapecurve)+'.worldSpace',namePoci+'.inputCurve')
                mc.connectAttr(namePoci+'.result.position',str(templeloc)+'.translate')
                mc.setAttr(namePoci+'.parameter',parameter)
                
               
                
                if IFrotate==True:
                    mc.orientConstraint(templeloc,i,maintainOffset=IFMO)
                    mc.tangentConstraint(curvename,templeloc)
                    mc.parentConstraint(templeloc,i,maintainOffset=IFMO)
                else:
                    mc.pointConstraint(templeloc,i,maintainOffset=IFMO)
                
        
    ##----------------------------------------------------------------------------------------------
    def getSpace(self,obj):
            '''get one object's worldSpace value'''
            objT = mc.xform(obj,q=1,t=1,ws=1)
            objR = mc.xform(obj,q=1,ro=1,ws=1)
            aboutObjDate = objT + objR
            return aboutObjDate
    
    
    def node_by_name(self,name, root = om.MObject.kNullObj):
            dagiter = om.MItDag(om.MItDag.kDepthFirst)
            if not root is om.MObject.kNullObj:
                dagiter.reset(root)
            while not dagiter.isDone():
                pf = om.MFnDagNode(dagiter.currentItem())
                if pf.name() == name:
                    return dagiter.currentItem()
                dagiter.next()
            return om.MObject.kNullObj
    
    def getParam(self,crv , obj):
    
            curveshape = mc.listRelatives(crv,s=True)
            objspace = self.getSpace(obj)
    
            curveObj = self.node_by_name(curveshape[0])
            curveFn = om.MFnNurbsCurve(curveObj)
            mpoint = om.MPoint( objspace[0],objspace[1],objspace[2],1.0)
            nearestPoint = curveFn.closestPoint(mpoint,None,0.0001,om.MSpace.kTransform )
            u_util = om.MScriptUtil()
            uPtr = u_util.asDoublePtr()
            curveFn.getParamAtPoint(nearestPoint,uPtr,om.MSpace.kTransform)
            u1 = u_util.getDouble(uPtr)
            return u1